package cn.jit.ssm.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提取validator验证器的错误信息
 * @author: Cecurio
 * @create: 2017-12-08 20:09
 **/
public class BindingResultErrorExtraction {
    private static final Logger logger = LoggerFactory.getLogger(BindingResultErrorExtraction.class);

    /**
     *
     * @param result validator验证器的错误信息
     * @return 把错误信息放进Map
     */
    public static Map<String, String> putErrorsToMap(BindingResult result) {
        Map<String, String> map = new HashMap<String, String>();

        List<FieldError> list = result.getFieldErrors();

        for (FieldError error : list) {
            logger.error("error.getField(): " + error.getField());
            logger.error("error.getDefaultMessage(): " + error.getDefaultMessage());
            map.put(error.getField(), error.getDefaultMessage());
        }

        return map;
    }
}
